
import { pAjax } from "../../index/javascripts/gather";
// 获取元素
const cateBox = document.querySelector('.cate')
const contentBox = document.querySelector('.content')
const paginationBox = document.querySelector('.pagination')
const filterBox = document.querySelector('.filter')
const saleBox = document.querySelector('.sale')
const sortBox = document.querySelector('.sort')
const searchBox = document.querySelector('.search')

getCateGory()
async function getCateGory() {
    // 发送请求获取具体的商品分类信息
    let res = await pAjax({
        url: 'http://localhost:8888/goods/category',
        dataType: 'json'
    })
    // console.log(res);
    // 把后端返回的数据渲染到页面上
    let str = '<li class="active">全部</li>'
    // 循环拿到每一条数据
    res.list.forEach(item => {
        str += `
        <li>${item}</li>
        `
    })
    cateBox.innerHTML = str
}


// 首先我们要做的就是把我么的参数准备好
const info = {
    current: 1,
    pagesize: 12,
    search: '',
    filter: '',
    saleType: 10,
    sortType: 'id',
    sortMethod: 'ASC',
    category: ''
}

getGoodsList()
async function getGoodsList() {
    // 发送请求
    let res = await pAjax({
        url: 'http://localhost:8888/goods/list',
        data: info,
        dataType: 'json'
    })
    console.log(res);
    let str = ''
    res.list.forEach(item => {
        str += `
        <li data-id=${item.goods_id}>
            <div class="show">
                <img src="${item.img_big_logo}" alt="">
                <span class="hot ${item.is_hot ? 'active' : ''}">热销</span>
                <span class="sale ${item.is_sale ? 'active' : ''}">折扣</span>
            </div>
            <div class="info">
                <p class="title">${item.title}</p>
                <p class="price">
                    <span class="current">￥ ${item.current_price}</span>
                    <span class="old">￥ ${item.price}</span>
                </p>
                <button data-id=${item.goods_id}>加入购物车</button>
            </div>
        </li>
        `
    })
    contentBox.innerHTML = str
    paginationBox.innerHTML = `
        <p>分页</p>
        <div>
            <span class="left${info.current === 1 ? ' disable' : ''}">&lt;</span>
            <span>${info.current} / ${res.total}</span>
            <span class="right${info.current === res.total ? ' disable' : ''}">&gt;</span>
        </div>
        <select>
            <option value="12">12</option>
            <option value="16">16</option>
            <option value="20">20</option>
            <option value="24">24</option>
        </select>
        <input type="text" value="${info.current}">
        <button data-total=${res.total}>跳转</button>
    `
    // 获取select元素
    let select = document.querySelector('select')
    select.value = info.pagesize
}

// 分类信息的实现
cateBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.nodeName !== 'LI') return
    for (let i = 0; i < cateBox.children.length; i++) {
        cateBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.category = target.innerText === '全部' ? '' : target.innerText
    info.current = 1
    getGoodsList()
})

// 点击筛选按钮
filterBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    // 判断你点击的是不是某个元素
    if (target.nodeName !== 'LI') return
    for (let i = 0; i < filterBox.children.length; i++) {
        filterBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.filter = target.dataset.type
    info.current = 1
    getGoodsList()
})

// 点击折扣按钮
saleBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.nodeName !== 'LI') return
    for (let i = 0; i < saleBox.children.length; i++) {
        saleBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.saleType = target.dataset.type
    info.current = 1
    getGoodsList()
})

// 点击排序按钮
sortBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    // 判断你点击的是不是某个元素
    if (target.nodeName !== 'LI') return
    for (let i = 0; i < sortBox.children.length; i++) {
        sortBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.sortType = target.dataset.type
    info.sortMethod = target.dataset.method
    getGoodsList()
})

// 模糊搜索
searchBox.addEventListener('input', () => {
    info.search = searchBox.value.trim()
    info.current = 1
    getGoodsList()
})
// 分页的实现
paginationBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.className === 'right') {
        info.current++
        getGoodsList()
    }
    if (target.className === 'left') {
        info.current--
        getGoodsList()
    }
    if (target.nodeName === 'BUTTON') {
        let num = target.previousElementSibling.value - 0
        let total = target.dataset.total - 0
        if (!num) num = 1
        if (num < 0) num = 1
        if (num > total) num = total
        info.current = num
        getGoodsList()
    }
})
// 下来框的事件
paginationBox.addEventListener('change', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.nodeName === 'SELECT') {
        info.pagesize = target.value
        getGoodsList()
    }
})

// 我们依旧使用事件委托的方式来是实现
contentBox.addEventListener('click', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    console.log(target);
    // 判断点击的元素
    if (target.nodeName === 'LI') {
        window.sessionStorage.setItem('goodsId', target.dataset.id)
        window.location.href = './detail.html'
    }
    if (target.nodeName === 'BUTTON') {
        addCart(target.dataset.id)
    }
})

// 函数定义到外面
async function addCart(goodsId) {
    let id = window.localStorage.getItem('id')
    let token = window.localStorage.getItem('token')
    // 判断id和token
    if (!id || !token) {
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }

    // 发送请求
    let res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        method: 'post',
        data: { id, goodsId },
        dataType: 'json',
        headers: { authorization: token }
    })
    // 判断code是不是等于1
    if (res.code !== 1) {
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }
    alert('恭喜您添加成功')
}